import {useNavigate, useParams} from "react-router-dom";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import {useCallback, useEffect, useState} from "react";
import {Badge, Button, Card, Divider, message, Popconfirm, Spin, Tag, Tooltip, Typography} from "antd";
import {
    ArrowLeftOutlined,
    CalendarOutlined,
    CheckCircleOutlined,
    CheckOutlined,
    ClockCircleOutlined,
    CloseCircleOutlined,
    CloseOutlined,
    CodeOutlined,
    CopyOutlined,
    DeleteOutlined,
    FileTextOutlined,
    FormOutlined,
    InfoCircleOutlined,
    LinkOutlined,
    PlayCircleOutlined,
    StopOutlined,
    SyncOutlined,
    UndoOutlined
} from "@ant-design/icons";
import TaskEdit from "../../../components/console/task/taskEdit";

// 引入类型定义（如果有）
/**
 * 定时任务详情类型定义
 * @typedef {Object} TaskDetail
 * @property {string} taskName - 任务名称
 * @property {string} taskDescription - 任务描述
 * @property {string} serviceName - 服务名
 * @property {string} uri - 调用接口
 * @property {string} lastExecuteTime - 上次执行时间
 * @property {string} nextExecuteTime - 下次执行时间
 * @property {string} cronExpression - cron表达式
 * @property {string} cronDescription - cron描述
 * @property {number} lastExecuteStatus - 上次执行状态
 * @property {string} lastExecuteStatusValue - 上次执行状态文本
 * @property {string} lastExecuteResponse - 上次执行返回信息
 * @property {number} startStatus - 开启状态
 * @property {string} startStatusValue - 开启状态文本
 * @property {number} executeCount - 执行次数
 * @property {string} id - 任务ID
 */

const {Title, Text, Paragraph} = Typography;

/**
 * 定时任务详情页面
 * 设计风格参考：服务治理详情页面
 * 核心特点：卡片式布局、左侧特色边框、统一视觉风格、友好交互体验
 */
const ConsoleTaskDetail = () => {
    const navigate = useNavigate();
    // 路由参数获取
    const {taskId, operation} = useParams();
    // 消息提示实例
    const [messageApi, contextHolder] = message.useMessage();
    // 加载状态
    const [loading, setLoading] = useState(true);
    // 定时任务详情数据
    const [taskDetail, setTaskDetail] = useState(/** @type {TaskDetail} */({}));
    // 复制状态
    const [copyStatus, setCopyStatus] = useState({id: '', text: '复制'});
    // 编辑定时任务模态框组件
    const [editTaskModalVisible, setEditTaskModalVisible] = useState(false);

    /**
     * 根据ID查询定时任务详情
     * 包含加载状态管理和异常处理
     * 用useCallback包裹查询方法，确保引用稳定
     */
    const searchScheduledTaskById = useCallback(() => {
        setLoading(true);
        RequestUtils.post(RequestApis.taskManage.searchById, {
            id: taskId
        }).then(res => {
            setTaskDetail(res.data.data || {});
            setLoading(false);
        }).catch(err => {
            messageApi.error(err.message || "获取定时任务详情失败");
            setLoading(false);
        });
    }, [taskId, messageApi]); // 依赖taskId和messageApi，这两个变化时才重新创建函数

    /**
     * 删除定时任务（仅编辑模式显示）
     */
    const removeScheduledTaskById = () => {
        RequestUtils.post(RequestApis.taskManage.removeById, {
            id: taskId
        }).then(res => {
            messageApi.success("删除定时任务成功，即将返回任务列表页面").then(() => {
                navigate('/console/task'); // 假设任务列表路由
            });
        }).catch(err => messageApi.error(err.message || "删除定时任务失败"));
    };

    /**
     * 手动执行一次定时任务
     */
    const execute = () => {
        RequestUtils.post(RequestApis.taskManage.execute, {
            id: taskId
        }).then(res => {
            messageApi.success("任务已经开始执行，请稍后刷新页面查看执行状态");
        }).catch(err => messageApi.error(err.message || "任务开始执行失败"));
    }

    /**
     * 修改定时任务开关状态
     */
    const editScheduledTaskStatus = (status) => {
        RequestUtils.post(RequestApis.taskManage.editStatus, {
            id: taskId,
            status: status
        }).then(res => {
            searchScheduledTaskById();
            messageApi.success(status ? "定时任务已开启" : "定时任务已关闭");
        }).catch(err => messageApi.error(err.message))
    }

    /**
     * 复制文本到剪贴板
     * @param {string} text - 要复制的文本
     * @param {string} id - 复制区域标识
     */
    const copyToClipboard = (text, id) => {
        navigator.clipboard.writeText(text).then(() => {
            setCopyStatus({id, text: '已复制'});
            setTimeout(() => {
                if (copyStatus.id === id) {
                    setCopyStatus({id: '', text: '复制'});
                }
            }, 2000);
        }).catch(() => {
            messageApi.error('复制失败，请手动复制');
        });
    };

    const formatJsonContent = (content) => {
        // 复制功能处理
        const handleCopy = () => {
            navigator.clipboard.writeText(content).then(() => {
                setCopyStatus({id: 'response', text: '已复制'});
                setTimeout(() => setCopyStatus({id: '', text: '复制'}), 2000);
            }).catch(() => messageApi.error('复制失败，请手动复制'));
        };

        // 尝试解析JSON
        try {
            const parsedJson = JSON.parse(content);
            const formattedJson = JSON.stringify(parsedJson, null, 2);

            // 创建临时元素处理高亮（避免正则替换污染）
            const div = document.createElement('div');
            div.style.whiteSpace = 'pre';
            div.style.fontFamily = 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace';

            // 使用更安全的JSON高亮库逻辑（模拟）
            let html = formattedJson
                // 先匹配键名（确保只匹配键名部分）
                .replace(/"([^"]+)"\s*:/g, (match, key) => {
                    return `<span style="color: #2563eb; font-weight: bold;">"${key}"</span>:`;
                })
                // 匹配字符串值（排除键名后的引号）
                .replace(/(?<=:|,)\s*"([^"\\]*(?:\\.[^"\\]*)*)"/g, (match, value) => {
                    return `<span style="color: #059669;">"${value}"</span>`;
                })
                // 匹配数字
                .replace(/(?<=:|,)\s*(-?\d+(\.\d+)?([eE][+-]?\d+)?)/g, (match) => {
                    return `<span style="color: #dc2626;">${match}</span>`;
                })
                // 匹配布尔值
                .replace(/(?<=:|,)\s*(true|false)/g, (match) => {
                    return `<span style="color: #7c3aed; font-weight: bold;">${match}</span>`;
                })
                // 匹配null
                .replace(/(?<=:|,)\s*(null)/g, (match) => {
                    return `<span style="color: #6b7280; font-style: italic;">${match}</span>`;
                });

            return (
                <div>
                    <div style={{display: 'flex', justifyContent: 'flex-end', marginBottom: 8}}>
                        <Button
                            icon={<CopyOutlined/>}
                            size="small"
                            onClick={handleCopy}
                            style={{padding: '2px 8px', height: 'auto'}}
                        >
                            {copyStatus.id === 'response' ? copyStatus.text : '复制'}
                        </Button>
                    </div>
                    <div dangerouslySetInnerHTML={{__html: html}}/>
                </div>
            );
        } catch (e) {
            // 非JSON内容直接展示
            return (
                <div>
                    <div style={{display: 'flex', justifyContent: 'flex-end', marginBottom: 8}}>
                        <Button
                            icon={<CopyOutlined/>}
                            size="small"
                            onClick={handleCopy}
                            style={{padding: '2px 8px', height: 'auto'}}
                        >
                            {copyStatus.id === 'response' ? copyStatus.text : '复制'}
                        </Button>
                    </div>
                    {content}
                </div>
            );
        }
    };

    /**
     * 页面初始化时加载数据
     * 监听taskId变化，重新加载数据
     */
    useEffect(() => {
        // 1. 页面初始化时立即执行一次查询
        searchScheduledTaskById();

        // 2. 设置定时器：每隔10秒（10000毫秒）执行一次查询
        const timerId = setInterval(() => {
            searchScheduledTaskById();
        }, 10000);

        // 3. 清理函数：组件卸载或taskId变化时，清除定时器
        return () => {
            clearInterval(timerId);
        };
    }, [taskId, searchScheduledTaskById]); // 依赖taskId和稳定的查询函数

    // ------------------------------ 工具函数 ------------------------------
    /**
     * 获取执行状态标签（带图标和颜色）
     * @param {number} status - 执行状态码
     * @returns {JSX.Element} 状态标签
     */
    const getExecuteStatusTag = (status) => {
        const statusConfig = [
            {code: 0, text: "未执行", color: "default", icon: <ClockCircleOutlined/>},
            {code: 1, text: "执行中", color: "processing", icon: <SyncOutlined spin/>},
            {code: 2, text: "执行成功", color: "success", icon: <CheckCircleOutlined/>},
            {code: 3, text: "执行失败", color: "error", icon: <CloseCircleOutlined/>}
        ];
        const config = statusConfig.find(item => item.code === status) ||
            {code: -1, text: "未知状态", color: "default", icon: <InfoCircleOutlined/>};

        return (
            <Tag
                color={config.color}
                icon={config.icon}
                style={{borderRadius: '16px', padding: '4px 12px'}}
            >
                {config.text}
            </Tag>
        );
    };

    /**
     * 获取启用状态标签（带图标和颜色）
     * @param {number} status - 启用状态码
     * @returns {JSX.Element} 状态标签
     */
    const getStartStatusTag = (status) => {
        const statusConfig = [
            {code: 0, text: "已关闭", color: "default", icon: <StopOutlined/>},
            {code: 1, text: "已开启", color: "success", icon: <PlayCircleOutlined/>}
        ];
        const config = statusConfig.find(item => item.code === status) ||
            {code: -1, text: "未知状态", color: "default", icon: <InfoCircleOutlined/>};

        return (
            <Tag
                color={config.color}
                icon={config.icon}
                style={{borderRadius: '16px', padding: '4px 12px'}}
            >
                {config.text}
            </Tag>
        );
    };

    // ------------------------------ 基础样式配置 ------------------------------
    // 通用卡片样式（统一视觉风格）
    const baseCardStyle = {
        marginBottom: '24px',
        borderRadius: '12px',
        border: '1px solid #e0e0e0',
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
        transition: 'all 0.3s ease',
        overflow: 'hidden'
    };

    // 卡片悬停样式
    const cardHoverStyle = {
        boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)',
        transform: 'translateY(-2px)'
    };

    // 状态颜色映射（统一色彩系统）
    const statusColorMap = {
        executeSuccess: '#10b981',
        executeFailed: '#ef4444',
        executing: '#3b82f6',
        unExecuted: '#6b7280',
        enabled: '#10b981',
        disabled: '#6b7280'
    };

    // 卡片左侧边框颜色
    const cardBorderColors = {
        primary: '#3b82f6',    // 蓝色 - 主信息
        secondary: '#10b981',  // 绿色 - 执行记录
        accent: '#f59e0b'      // 橙色 - 其他信息
    };

    // ------------------------------ 页面渲染 ------------------------------
    return (
        <div style={{padding: '24px'}}>
            {/* 消息提示容器（必须放在最前面） */}
            {contextHolder}

            {/* 1. 顶部返回按钮区域 */}
            <div style={{marginBottom: '24px'}}>
                <div style={{
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    flexWrap: 'wrap',
                    gap: '16px'
                }}>
                    {/* 返回按钮 */}
                    <Button
                        type="primary"
                        onClick={() => navigate('/console/task')} // 假设任务列表路由
                        style={{
                            borderRadius: '20px',
                            padding: '6px 20px',
                            backgroundColor: '#3b82f6',
                            borderColor: '#3b82f6',
                            transition: 'all 0.3s ease',
                            display: 'inline-flex',
                            alignItems: 'center',
                            boxShadow: '0 2px 8px rgba(59, 130, 246, 0.2)',
                            width: '300px'
                        }}
                        hoverStyle={{
                            backgroundColor: '#2563eb',
                            boxShadow: '0 4px 16px rgba(59, 130, 246, 0.3)',
                            borderColor: '#2563eb',
                            transform: 'translateY(-1px)'
                        }}
                    >
                        <ArrowLeftOutlined style={{marginRight: '6px'}}/>
                        返回定时任务列表
                    </Button>

                    {/* 编辑模式下显示操作按钮 */}
                    <div>
                        <Button
                            color='purple'
                            variant='solid'
                            style={{marginRight: '12px', width: '180px'}}
                            onClick={() => editScheduledTaskStatus(taskDetail.startStatus === 1 ? 0 : 1)}
                        >
                            {taskDetail.startStatus === 1 ?
                                <span><CloseOutlined style={{marginRight: '6px'}}/>关闭定时任务</span> :
                                <span><CheckOutlined style={{marginRight: '6px'}}/>开启定时任务</span>}
                        </Button>
                        <Button
                            color='pink'
                            variant='outlined'
                            style={{marginRight: '12px', width: '180px'}}
                            onClick={() => execute()}
                        >
                            <UndoOutlined/>
                            手动执行一次
                        </Button>

                        {operation === "edit" &&
                            <Popconfirm
                                placement="leftTop"
                                title="删除定时任务确认"
                                description="确定要删除当前定时任务？删除后任务将停止执行且数据无法恢复。"
                                okText="确认"
                                cancelText="取消"
                                onConfirm={removeScheduledTaskById}
                            >
                                <Button
                                    type="primary"
                                    danger
                                    style={{
                                        borderRadius: '20px',
                                        padding: '6px 20px',
                                        transition: 'all 0.3s ease',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        boxShadow: '0 2px 8px rgba(239, 68, 68, 0.2)',
                                        width: '240px'
                                    }}
                                    hoverStyle={{
                                        boxShadow: '0 4px 16px rgba(239, 68, 68, 0.3)',
                                        transform: 'translateY(-1px)'
                                    }}
                                >
                                    <DeleteOutlined style={{marginRight: '6px'}}/>
                                    删除当前定时任务
                                </Button>
                            </Popconfirm>}

                    </div>
                </div>
            </div>

            {/* 2. 任务标题卡片（核心信息展示） */}
            <Card
                style={baseCardStyle}
                loading={loading}
                hoverable
                bodyStyle={{padding: '24px'}}
            >
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    flexWrap: 'wrap',
                    gap: '16px'
                }}>
                    {/* 任务名称和ID */}
                    <div style={{marginBottom: '16px'}}>
                        <Title level={2} style={{margin: 0, color: '#111827', display: 'flex', alignItems: 'center'}}>
                            <CalendarOutlined style={{marginRight: '8px', color: cardBorderColors.primary}}/>
                            {taskDetail.taskName || '未命名任务'}
                        </Title>
                        <div style={{display: 'flex', alignItems: 'center', marginTop: '8px'}}>
                            <Text style={{color: '#6b7280', fontSize: '14px'}}>
                                任务ID: {taskDetail.id || '未知ID'}
                            </Text>
                            <Button
                                icon={<CopyOutlined/>}
                                size="small"
                                onClick={() => copyToClipboard(taskDetail.id || '', 'taskId')}
                                style={{marginLeft: '8px', padding: '0 6px', height: '24px'}}
                            >
                                {copyStatus.id === 'taskId' ? copyStatus.text : '复制'}
                            </Button>
                        </div>
                    </div>

                    {/* 状态标签组 */}
                    <div style={{display: 'flex', gap: '16px', alignItems: 'center', flexWrap: 'wrap'}}>
                        {/* 运行状态 */}
                        <div style={{display: 'flex', alignItems: 'center'}}>
                            <Text style={{color: '#4b5563', marginRight: '8px'}}>运行状态：</Text>
                            {getStartStatusTag(taskDetail.startStatus)}
                        </div>

                        {/* 执行状态 */}
                        <div style={{display: 'flex', alignItems: 'center'}}>
                            <Text style={{color: '#4b5563', marginRight: '8px'}}>执行状态：</Text>
                            {getExecuteStatusTag(taskDetail.lastExecuteStatus)}
                        </div>
                    </div>
                </div>
            </Card>

            {/* 3. 任务基本信息卡片 */}
            <Card
                title={
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        color: '#111827'
                    }}>
                        <div>
                            <InfoCircleOutlined style={{marginRight: '8px', color: cardBorderColors.primary}}/>
                            基本信息
                            <Badge
                                count="基础配置"
                                style={{
                                    marginLeft: '10px',
                                    backgroundColor: 'rgba(59, 130, 246, 0.15)',
                                    color: cardBorderColors.primary
                                }}
                            />
                        </div>
                        {operation === 'edit' ?
                            <div>
                                <Button
                                    color='purple'
                                    variant='solid'
                                    style={{width: '260px'}}
                                    onClick={() => setEditTaskModalVisible(true)}
                                >
                                    <FormOutlined style={{marginRight: '8px'}}/>
                                    编辑定时任务
                                </Button>
                            </div> :
                            <div/>}
                    </div>
                }
                style={{
                    ...baseCardStyle,
                    borderLeft: `4px solid ${cardBorderColors.primary}`, // 蓝色边框标识基础信息
                }}
                loading={loading}
                hoverable
                bodyStyle={{padding: '24px'}}
                onMouseEnter={e => {
                    e.currentTarget.style.boxShadow = cardHoverStyle.boxShadow;
                    e.currentTarget.style.transform = cardHoverStyle.transform;
                }}
                onMouseLeave={e => {
                    e.currentTarget.style.boxShadow = baseCardStyle.boxShadow;
                    e.currentTarget.style.transform = 'translateY(0)';
                }}
            >
                {/* 网格布局展示基本信息 */}
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
                    gap: '24px 16px'
                }}>
                    {/* 服务名称 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <LinkOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>服务名称</Text>
                        </div>
                        <Text style={{fontSize: '15px', color: '#111827'}}>
                            {taskDetail.serviceName || '-'}
                        </Text>
                    </div>

                    {/* 调用接口 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <LinkOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>调用接口</Text>
                        </div>
                        <Tooltip title={taskDetail.uri || '无接口信息'}>
                            <Text
                                style={{fontSize: '15px', color: cardBorderColors.primary, wordBreak: 'break-all'}}
                                ellipsis={{rows: 1, expandable: true, symbol: '显示'}}
                            >
                                {taskDetail.uri || '-'}
                            </Text>
                        </Tooltip>
                    </div>

                    {/* 执行次数 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <SyncOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>执行次数</Text>
                        </div>
                        <Text style={{fontSize: '15px', color: '#111827'}}>
                            {taskDetail.executeCount || 0} 次
                        </Text>
                    </div>

                    {/* 空列占位 */}
                    <div></div>

                    {/* 上次执行时间 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <ClockCircleOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>上次执行时间</Text>
                        </div>
                        <Text style={{fontSize: '15px', color: '#111827'}}>
                            {taskDetail.lastExecuteTime || '未执行'}
                        </Text>
                    </div>

                    {/* 下次执行时间 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <CalendarOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>下次执行时间</Text>
                        </div>
                        <Text style={{fontSize: '15px', color: statusColorMap.enabled}}>
                            {taskDetail.nextExecuteTime || '未设置'}
                        </Text>
                    </div>

                    {/* Cron表达式展示优化（无背景，仅文字样式调整） */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <CodeOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>Cron表达式</Text>
                            <Tooltip title="Cron表达式格式：秒 分 时 日 月 周 [年]">
                                <InfoCircleOutlined
                                    style={{marginLeft: '8px', color: '#9ca3af', fontSize: '14px', cursor: 'help'}}/>
                            </Tooltip>
                        </div>

                        <div style={{display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap'}}>
                            {/* Cron表达式文字展示 */}
                            <div
                                style={{
                                    flexGrow: 1,
                                    fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace', // 等宽字体保持格式对齐
                                    fontSize: '14px',
                                    fontWeight: '600', // 加粗
                                    color: '#2563eb', // 主色调蓝色，醒目且不刺眼
                                    wordBreak: 'break-all'
                                }}
                            >
                                {taskDetail.cronExpression || '-'}
                            </div>
                        </div>
                    </div>

                    {/* Cron描述 */}
                    <div>
                        <div style={{display: 'flex', alignItems: 'center', marginBottom: '6px'}}>
                            <InfoCircleOutlined
                                style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                            <Text strong style={{color: '#4b5563', fontSize: '14px'}}>Cron描述</Text>
                        </div>
                        <Text style={{fontSize: '15px', color: '#111827'}}>
                            {taskDetail.cronDescription || '-'}
                        </Text>
                    </div>
                </div>

                {/* 任务描述（单独区域） */}
                <Divider style={{margin: '20px 0'}}/>
                <div>
                    <div style={{display: 'flex', alignItems: 'center', marginBottom: '8px'}}>
                        <FileTextOutlined
                            style={{marginRight: '6px', color: cardBorderColors.primary, fontSize: '14px'}}/>
                        <Text strong style={{color: '#4b5563', fontSize: '14px'}}>任务描述</Text>
                    </div>
                    <Paragraph
                        style={{
                            fontSize: '15px',
                            lineHeight: '1.8',
                            padding: '16px',
                            backgroundColor: '#f9fafb',
                            borderRadius: '8px',
                            margin: 0,
                            color: '#111827',
                            border: '1px solid #e5e7eb',
                            transition: 'all 0.2s ease',
                        }}
                        hoverStyle={{
                            backgroundColor: '#f3f4f6',
                        }}
                    >
                        {taskDetail.taskDescription || '无任务描述信息'}
                    </Paragraph>
                </div>
            </Card>

            {/* 4. 执行记录卡片 */}
            <Card
                title={
                    <div style={{display: 'flex', alignItems: 'center', color: '#111827'}}>
                        <SyncOutlined style={{marginRight: '8px', color: cardBorderColors.secondary}}/>
                        最近执行记录
                        <Badge
                            count="执行详情"
                            style={{
                                marginLeft: '10px',
                                backgroundColor: 'rgba(16, 185, 129, 0.15)',
                                color: cardBorderColors.secondary
                            }}
                        />
                    </div>
                }
                style={{
                    ...baseCardStyle,
                    borderLeft: `4px solid ${cardBorderColors.secondary}`, // 绿色边框标识执行记录
                }}
                loading={loading}
                hoverable
                bodyStyle={{padding: '24px'}}
                onMouseEnter={e => {
                    e.currentTarget.style.boxShadow = cardHoverStyle.boxShadow;
                    e.currentTarget.style.transform = cardHoverStyle.transform;
                }}
                onMouseLeave={e => {
                    e.currentTarget.style.boxShadow = baseCardStyle.boxShadow;
                    e.currentTarget.style.transform = 'translateY(0)';
                }}
            >
                {/* 执行状态概览 */}
                <div style={{
                    marginBottom: '20px',
                    display: 'flex',
                    flexWrap: 'wrap',
                    gap: '16px',
                    alignItems: 'center'
                }}>
                    <div style={{display: 'flex', alignItems: 'center'}}>
                        <Text style={{color: '#4b5563', marginRight: '8px'}}>执行状态：</Text>
                        {getExecuteStatusTag(taskDetail.lastExecuteStatus)}
                    </div>
                    {taskDetail.lastExecuteStatus === 3 && (
                        <Tag color="error" style={{borderRadius: '12px', cursor: 'default'}}>
                            <CloseCircleOutlined style={{marginRight: '4px'}}/>
                            执行失败，请检查任务配置
                        </Tag>
                    )}
                </div>

                {/* 执行结果展示 */}
                <div>
                    <div style={{display: 'flex', alignItems: 'center', marginBottom: '12px'}}>
                        <Text strong style={{color: '#4b5563', fontSize: '14px'}}>
                            上次执行返回信息：
                        </Text>
                    </div>

                    {taskDetail.lastExecuteResponse ? (
                        <div
                            style={{
                                backgroundColor: taskDetail.lastExecuteStatus === 3 ? '#fff1f0' : '#f9fafb',
                                padding: '20px',
                                borderRadius: '8px',
                                fontSize: '14px',
                                lineHeight: '1.8',
                                whiteSpace: 'pre-wrap',
                                fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace',
                                border: taskDetail.lastExecuteStatus === 3 ? '1px solid #fecaca' : '1px solid #e5e7eb',
                                color: taskDetail.lastExecuteStatus === 3 ? '#dc2626' : '#111827',
                                transition: 'all 0.3s ease',
                                maxHeight: '500px',
                                overflow: 'auto'
                            }}
                        >
                            {formatJsonContent(taskDetail.lastExecuteResponse)}
                        </div>
                    ) : (
                        <div style={{
                            textAlign: 'center',
                            padding: '40px 0',
                            color: '#6b7280',
                            backgroundColor: '#f9fafb',
                            borderRadius: '8px',
                            border: '1px dashed #e5e7eb',
                            transition: 'all 0.2s ease'
                        }}>
                            <ClockCircleOutlined style={{fontSize: '40px', marginBottom: '16px', opacity: 0.5}}/>
                            <p>暂无执行记录</p>
                        </div>
                    )}
                </div>
            </Card>

            {/* 5. 加载状态占位（全局加载时显示） */}
            {loading && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(255, 255, 255, 0.7)',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    zIndex: 9999,
                    backdropFilter: 'blur(2px)'
                }}>
                    <Spin size="large" tip="加载定时任务详情中..."/>
                </div>
            )}

            {/* 定时任务编辑模态框 */}
            <TaskEdit
                visible={editTaskModalVisible}
                setVisible={setEditTaskModalVisible}
                taskDetail={taskDetail}
                searchScheduledTaskById={searchScheduledTaskById}
            />
        </div>
    );
};

export default ConsoleTaskDetail;